package com.example.seakdreamandroid.voiceCommunity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.whiteNoise.SleepFriendChannel;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class VoiceDescribeActivity extends AppCompatActivity {
    private Intent intent;
    private Bundle bundle;
    private List<AudioInfo> channels;
    private static String CHANNEL;
    private EditText title,content;
    private TextView sendTitile,musicName;
    private String music = "";
    private SleepFriendChannel sleepFriendChannel = new SleepFriendChannel();
    private Button share;
    private FormBody body;
    private ImageView returnButton;
    private TextView cancel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_describe);
        intent = getIntent();
        bundle = intent.getExtras();
        CHANNEL = bundle.getString("channel");
//        if(CHANNEL.equals("freeconbination")){
//            channels = new ArrayList<AudioInfo>();
//            channels = (List) bundle.getSerializable("mlist");
//            positions = bundle.getIntegerArrayList("positions");
//
//        }else
        channels = (List<AudioInfo>) bundle.getSerializable("mlist");
        init();
        setListener();




    }

    private void setListener() {
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sleepFriendChannel.setUserContent(content.getText().toString());
                sleepFriendChannel.setTitle(title.getText().toString());
                SecureRandom secureRandom = null;
                try {
                    secureRandom = SecureRandom.getInstance("SHA1PRNG");
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                secureRandom.setSeed(10000L);
                User user = (User) getApplication();
                String URL = Constant.BASE_URL +  "WhiteNoise/VoiceDescribe/addSleepFriendCreation?";
                FormBody.Builder builder = new FormBody.Builder()
                        .add("id", UUID.randomUUID().toString())
                        .add("userId",user.getUserId())
//                        .add("postTime", String.valueOf(sleepFriendChannel.getPostTime()))
                        .add("userContent",sleepFriendChannel.getUserContent())
                        .add("count", String.valueOf(secureRandom.nextInt() % 500))
                        .add("save", String.valueOf(secureRandom.nextInt() % 50))
                        .add("musicImage1",sleepFriendChannel.getMusicImage1())
                        .add("musicImage2",sleepFriendChannel.getMusicImage2())
                        .add("musicImage3",sleepFriendChannel.getMusicImage3())
                        .add("title",sleepFriendChannel.getTitle());
                if(sleepFriendChannel.getSelectedId1() != null){
                    builder.add("selectedId1",sleepFriendChannel.getSelectedId1());
                }
                if(sleepFriendChannel.getSelectedId2() != null){
                    builder.add("selectedId2",sleepFriendChannel.getSelectedId2());
                }
                if(sleepFriendChannel.getSelectedId3() != null){
                    builder.add("selectedId3",sleepFriendChannel.getSelectedId3());
                }
                body = builder.build();

                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(URL)
                        .post(body)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.e("onFailure","请求失败");
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String responseBody = response.body().string();
                        Log.e("responseBody",responseBody);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(VoiceDescribeActivity.this,"分享成功",Toast.LENGTH_SHORT).show();
                            }
                        });


                        finish();


                    }
                });

            }
        });
    }

    public void init(){
        title = findViewById(R.id.voice_title);
        content = findViewById(R.id.voice_content);
        sendTitile = findViewById(R.id.voice_send_title);
        musicName = findViewById(R.id.voice_send_music_name);
        share = findViewById(R.id.voice_share_button);
        returnButton = findViewById(R.id.voice_describe_return);
        cancel = findViewById(R.id.voice_cancel);
        sleepFriendChannel.setSelectedId1(channels.size()>=1?channels.get(0).getAudioId():null);
        sleepFriendChannel.setSelectedId2(channels.size()>=2?channels.get(1).getAudioId():null);
        sleepFriendChannel.setSelectedId3(channels.size()>=3?channels.get(2).getAudioId():null);
//        if(CHANNEL.equals("freeconbination")){
//            for (int i=0;i<positions.size();i++){
//                AudioInfo audioInfo = (AudioInfo) channels.get(positions.get(i));
//                music += audioInfo.getAudioName() + "  ";
//                if(i == 0){
//                    sleepFriendChannel.setSelectedId1(audioInfo.getAudioId());
//                }else if(i == 1){
//                    sleepFriendChannel.setSelectedId2(audioInfo.getAudioId());
//                }else{
//                    sleepFriendChannel.setSelectedId3(audioInfo.getAudioId());
//                }
//            }
//        }else
//        if(CHANNEL.equals("OfficialRecommendation") || CHANNEL.equals("SleepFriendCreation") || CHANNEL.equals("FreeCombination")){
//            for (int i=0;i<channels.size();i++){
//                AudioInfo audioInfo = (AudioInfo) channels.get(i);
//                music += audioInfo.getAudioName() + "  ";
//                if(i == 0){
//                    sleepFriendChannel.setSelectedId1(audioInfo.getAudioId());
//                }else if(i == 1){
//                    sleepFriendChannel.setSelectedId2(audioInfo.getAudioId());
//                }else{
//                    sleepFriendChannel.setSelectedId3(audioInfo.getAudioId());
//                }
//            }
//        }
        musicName.setText(music);

        title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    sendTitile.setText(title.getText());
                    sleepFriendChannel.setTitle(title.getText().toString());
                }else{
                    sendTitile.setText(title.getText());
                    sleepFriendChannel.setTitle(title.getText().toString());
                }
            }
        });
        returnButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        sleepFriendChannel.setUserContent(content.getText().toString());
        sleepFriendChannel.setMusicImage1("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBdTV3NGhEeHNDcDdoSHZVZHRvVzZ5ZDNOYVZzP2U9c1JzWmc2.png");
        sleepFriendChannel.setMusicImage2("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBdTV3NGhEeHNDcDdoSHZVZHRvVzZ5ZDNOYVZzP2U9c1JzWmc2.png");
        sleepFriendChannel.setMusicImage3("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBdTV3NGhEeHNDcDdoSHZVZHRvVzZ5ZDNOYVZzP2U9c1JzWmc2.png");
        sleepFriendChannel.setUserId("1");
        sleepFriendChannel.setPostTime(new Date());
        sleepFriendChannel.setCount(0);
        sleepFriendChannel.setSave(0);



    }
}